<?php
/**
 * Created by PhpStorm.
 * User: costa92
 * Date: 2016/11/12
 * Time: 下午3:21
 */

namespace App\Libraries\classs;

use Redirect, Input, Response;
use zgldh\QiniuStorage\QiniuStorage;
use App\Models\Attachs;

class Upload
{
   public function __construct()
   {

   }

    static $instance;
    public static function  getInstance(){
        if( self::$instance==null ){
            self::$instance = new self();
        }
        return self::$instance;
    }
    //上传base64格式文件
    public function upload_base64($base64){
        if($base64){
            $disk = QiniuStorage::disk('qiniu');
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
                $ext = $result[2];
                $base64 = str_replace('data:image/'.$ext.';base64,', '', $base64);
            }else {
                return array('success' => false);
            }
            $file=base64_decode($base64);
            $file_name=$this->check(md5($base64.time()),$ext);
            $disk->put($file_name,$file);
            $attach_data=array(
                'name'=>$file_name,
                'path'=>$disk->imagePreviewUrl($file_name,''),
                'exts'=>$ext,
                'addtime'=>time(),
            );
            $attach =Attachs::create($attach_data);
            return array('success'=>true,'url'=>$disk->imagePreviewUrl($file_name,''),'id' => $attach->id);
        }
        return array('success' => false);
    }

    public function check($name,$ext){
        $disk = QiniuStorage::disk('qiniu');
        if($disk->exists($name.'.'.$ext)){
            $name=md5($name.time());
            $this->check($name,$ext);
        }
        return $name.'.'.$ext;
    }
}